<template>
  <el-tree-select v-model="selectedValue" :data="treeData" :props="defaultProps" check-strictly :render-after-expand="false" style="width: 240px" @change="handleChange" @node-click="nodeClick" />
</template>

<script setup>
import { ref, watch, onMounted } from "vue";
const props = defineProps({
  modelValue: {
    type: String,
    default: "",
  },
});
const treeData = [
  {
    id: "440000",
    name: "广东省",
    gridCode: "GD",
    level: 1,
    children: [
      {
        id: "440100",
        name: "广州市",
        gridCode: "GZ",
        level: 2,
      },
    ],
  },
];
const defaultProps = {
  value: "gridCode",
  label: "name",
  children: "children",
};

const selectedValue = ref("");

// 根据 v-model 初始值设置选中项
const setDefaultValue = () => {
  if (!props.modelValue) return;

  const findInTree = (tree) => {
    for (const node of tree) {
      if (node.gridCode === props.modelValue) {
        return node.gridCode;
      }
      if (node.children?.length) {
        const found = findInTree(node.children);
        if (found) return found;
      }
    }
    return null;
  };

  selectedValue.value = findInTree(treeData) || "";
};

const emit = defineEmits(["update:modelValue", "nodeClick"]);
// 处理选择变化
const handleChange = (value) => {
  emit("update:modelValue", value);
};

const nodeClick = (node) => {
  emit("nodeClick", node);
}

// 监听外部 modelValue 变化
watch(
  () => props.modelValue,
  (newVal) => {
    if (newVal !== selectedValue.value) {
      selectedValue.value = newVal;
    }
  }
);

// 初始化设置默认值
setDefaultValue();
</script>
